import { defineStore } from 'pinia'

export const userGoodsStore = defineStore({
    id:'goods',
    state:()=>({
        //在这里创建相关变量
        cartData:[],
        tmpData:[],
        orderData:[],
    }),
    actions:{
        //在这里面创建相关的方法
        cartAdd(val) {
            let tmp = JSON.parse(sessionStorage.getItem('cart'))
            if (tmp == null) {
                this.cartData.push(val)
            } else {
                this.cartData = tmp;
                this.tmpData = this.cartData.find(e => e.id == val.id)
                if (this.tmpData) {
                    this.tmpData.num += val.num
                    this.tmpData.total = this.tmpData.num * this.tmpData.onlineprice
                } else {
                    this.cartData.push(val)
                }
            }
            
            sessionStorage.setItem('cart', JSON.stringify(this.cartData))
        },
        //创建生成订单的方法
        orderAdd(val) {
            const tmp = JSON.parse(sessionStorage.getItem('order'))
            if (tmp == null) {
                this.orderData.push(val)
            } else {
                this.orderData = tmp
                this.orderData.push(val)
            }
            sessionStorage.setItem('order', JSON.stringify(this.orderData))
        }
    }
})